package com.bright.ghj.overt.task.timely;

import com.bright.ghj.overt.pojo.command.ImportAccessCommand;
import com.bright.ghj.overt.pojo.vo.SaveResultVO;
import com.bright.ghj.overt.service.BaseDataService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * @author hxj/Tz
 * @date 2024/02/07 15:03
 * @Description 导入Access的异步任务执行器实现
 */
@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public class AsyncAccessImportExecutor extends AsyncTaskExecutor {


    private static final String ASYNC_TASK_EXECUTOR_NAME = "导入Access任务处理器";

//    private JdbcTemplate jdbcTemplatePrimary;
////    private JdbcTemplate jdbcTemplateSecond;
//
//    private PlatformTransactionManager transactionManagerPrimary;
////    private PlatformTransactionManager transactionManagerSecond;
//
//    private DistZtManager distZtManager;
//    private OpenReportRecordManager openReportRecordManager;
//    private FileListManager fileListManager;
//    private BaseDataManager baseDataManager;
//    private EntityManager entityManager;
    private BaseDataService baseDataService;
    private ImportAccessCommand importAccessCommand;

    private String[] tableNames;
    private File accessFile;


    /**
     * 初始化设置执行器名称
     */
    public AsyncAccessImportExecutor() {
        super(ASYNC_TASK_EXECUTOR_NAME);
    }


    /**
     * 实际异步执行的任务体抽象方法、由具体的异步任务实现
     *
     * @return 执行结果
     * @throws Exception 可能出现的业务异常
     */
    @Override
    public boolean taskContent() {
        return handleUpload();
    }

    /**
     * 执行上传廉政平台逻辑
     *
     * @return 返回执行的结果
     */
    public boolean handleUpload() {
        try {
            int execCount = importAccessCommand.getTableNames().length;
            setProgressStepSize(PERCENTAGE / execCount);

            List<SaveResultVO> saveResultVOS = baseDataService.importAccess(importAccessCommand, accessFile, o -> this.advanceProgress());// 多传this 让方法内部可以调用advanceProgress等进度条推进的方法
            if (saveResultVOS.size() > 0) {
                SaveResultVO saveResultVO = saveResultVOS.get(0);
                if (saveResultVO.isSuccess()) {
                    return true;
                } else {
                    StringBuilder errorInfo = new StringBuilder();
                    for (String info : saveResultVO.getInfoList()) {
                        errorInfo.append(info).append("；");
                    }
                    setErrorInfo(errorInfo.toString());

                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    /**
//     * 执行上传廉政平台逻辑
//     *
//     * @return 返回执行的结果
//     */
//    public boolean handleUpload() {

        // 执行导入Access逻辑

        //实际执行的业务需要手动开启事务、手动提交回滚
//        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//        TransactionStatus primaryStatus = transactionManagerPrimary.getTransaction(def);
//
//
//        // 获取access数据库连接
//        try (Connection conToAccess = AccessDBUtil.initConnection(accessFile, "", "")) {
//            Statement fromSm = conToAccess.createStatement();
//
//            // readyDistInfo 读取地区信息----------------------------------
//            String fromDistId, toDistId, fromDistName;
//            Date fromDate1, fromDate2;
//            boolean fromDateAllFlag;
//            // 获取access的
//            List<List<Object>> accessDists = AccessDBUtil.getList(fromSm, "select distid,distName,date1,date2,date3,dateallflag from s_update");
//            if (accessDists.size() > 0) {
//                List<Object> accessDist = accessDists.get(0);
//                fromDistId = (String) accessDist.get(0);
//                fromDistName = (String) accessDist.get(1);
//                fromDate1 = DateUtil.parseDateString((String) accessDist.get(2));
//                fromDate2 = DateUtil.parseDateString((String) accessDist.get(3));
//                fromDateAllFlag = (boolean) accessDist.get(5);
//            } else {
//                throw new RuntimeException("准备工作readyDistInfo 读取access 地区信息错误: 获取不到s_update数据！");
//            }
//            // 获取区资产库的
//            DistDTO toDist = distZtManager.getDistByDistNameByCache(fromDistName);
//            if (toDist != null) {
//                toDistId = toDist.getDistNo();
//            } else {
//                throw new RuntimeException("准备工作readyDistInfo 读取access 地区信息错误: 数据库中未取到地区“" + fromDistName + "”！");
//            }
//            System.out.println("readyDistInfo完成");
//
//            // readyZts 读取账套信息-------------------------------------------
//            List<List<Object>> accessZts = AccessDBUtil.getList(fromSm, "select zth from zt where ztparent like '" + fromDistId + "%'");
//            List<String> fromZts = new ArrayList<>();
//            for (List<Object> accessZt : accessZts) {
//                String zth = StringUtil.trimToEmpty((String) accessZt.get(0));
//                zth = toDistId + StringUtil.right(zth, zth.length() - fromDistId.length());
//
////                String controlField = Constants.controlField;
////                if (!Constants.controlField.equalsIgnoreCase("")) {
////                    zth = getZth(StringUtil.trimToEmpty((String)((List)fromList.get(i)).get(0)), toDistId);
////                }
//                if (!StringUtil.isEmpty(zth)) {
//                    fromZts.add(zth);
//                }
//            }
//            if (fromZts.size() == 0) {
//                throw new RuntimeException("准备工作readyZts 读取access 账套信息错误: fromZts无数据！");
//            }
//            System.out.println("readyZts完成");
//
//
//            // workDist 采集dist表 从access取dist信息-------------------------
//            // 标记进度条总项数
//            int gaugeId = 0;
//            String sql = "select '" + toDistId + "'+right(地区编号,len(地区编号)-len('" + fromDistId + "')),地区名称 from dist where 地区编号 like '" +
//                    fromDistId + "%'";
//            accessDists = AccessDBUtil.getList(fromSm, sql);
//            for (List<Object> accessDist : accessDists) {
//                gaugeId += 1;
//
//                String distId = StringUtil.trimToEmpty((String) accessDist.get(0));
//                String distName = StringUtil.trimToEmpty((String) accessDist.get(1));
//                // 若区资产平台不存在该地区 则新增
//                if (distZtManager.getDistByDistNoByCache(distId) == null) {
//                    DistDTO newDist = new DistDTO();
//                    newDist.setDistNo(distId);
//                    newDist.setDistName(distName);
//                    distZtManager.insertNewDist(newDist);
//                }
//            }
//            System.out.println("workDist完成");
//
//            // workZt
//            // 区平台资产库的账套号列表//            List<String> toZts = new ArrayList<>();
//            // 保存账套对应关系 key=access的账套号（zth_import） value= 区平台账套号ztId
//            Map<String, String> ztMap = new HashMap<>();
//            String queryZtSql;
//            List<String> ztColumns = AccessDBUtil.getTableColumns(fromSm, "zt");
//            // 检测access中的账套表是否存在zbr dwfzr kjxm cnxm jdxz这些字段
//            if (!ztColumns.contains("zbr") || !ztColumns.contains("dwfzr") || !ztColumns.contains("kjxm")
//                    || !ztColumns.contains("cnxm") || !ztColumns.contains("jdxz")) {
//                queryZtSql = "select zth,ztdw,'" + toDistId + "',zth_old,checked,'' as zbr, '' as dwfzr, ''as kjxm, '' as  cnxm, '' as jdxz  from zt where ztparent like '" + fromDistId + "%'";
//            } else {
//                queryZtSql = "select zth,ztdw,'" + toDistId + "',zth_old,checked,zbr,  dwfzr, kjxm,  cnxm,  jdxz  from zt where ztparent like '" + fromDistId + "%'";
//            }
//            accessZts = AccessDBUtil.getList(fromSm, queryZtSql);
//            for (List<Object> accessZt : accessZts) {
//                gaugeId += 1;
//
//                // 根据zth_import找出对应区平台账套
//                String zthImport = (String) accessZt.get(0);
//                ZtDTO importZt = distZtManager.findByZthImportByCache(zthImport);
//                if (importZt == null) {
//                    continue;
//                }
//                String zth = importZt.getZtId();
////                toZts.add(zth);
//                ztMap.put(zthImport, zth);
////                String ztdw = StringUtil.trimToEmpty((String) accessZt.get(1));
////                String ztparent = StringUtil.trimToEmpty((String) accessZt.get(2));
////                String zth_old = StringUtil.trimToEmpty((String) accessZt.get(3));
////                boolean checked = (Boolean) accessZt.get(4);
//                String zbr = StringUtil.trimToEmpty((String) accessZt.get(5));
//                String dwfzr = StringUtil.trimToEmpty((String) accessZt.get(6));
//                String kjxm = StringUtil.trimToEmpty((String) accessZt.get(7));
//                String cnxm = StringUtil.trimToEmpty((String) accessZt.get(8));
//                String jdxz = StringUtil.trimToEmpty((String) accessZt.get(9));
//
//                Map<String, Object> updateZtParams = new HashMap<>();
//                if (StringUtil.isNotEmpty(zbr)) {
//                    updateZtParams.put("zbr", zbr);
//                }
//                if (StringUtil.isNotEmpty(dwfzr)) {
//                    updateZtParams.put("dwfzr", dwfzr);
//                }
//                if (StringUtil.isNotEmpty(kjxm)) {
//                    updateZtParams.put("kjxm", kjxm);
//                }
//                if (StringUtil.isNotEmpty(cnxm)) {
//                    updateZtParams.put("cnxm", cnxm);
//                }
//                if (StringUtil.isNotEmpty(jdxz)) {
//                    updateZtParams.put("jdxz", jdxz);
//                }
//                // 更新区平台的zbr dwfzr等字段
//                distZtManager.updateZtParamsByZtId(zth, updateZtParams);
//            }
//            System.out.println("workZt完成");
//
//            // workTable 插入数据
//            String fromYears1 = StringUtil.trimToEmpty(DateUtil.getYearOrMonthOrDay(fromDate1, Calendar.YEAR));
//            String fromYears2 = StringUtil.trimToEmpty(DateUtil.getYearOrMonthOrDay(fromDate2, Calendar.YEAR));
//            String fromMonths1 = StringUtil.trimToEmpty(DateUtil.getYearOrMonthOrDay(fromDate1, Calendar.MONTH));
//            String fromMonths2 = StringUtil.trimToEmpty(DateUtil.getYearOrMonthOrDay(fromDate2, Calendar.MONTH));
//
//            //因为上传逻辑是根据公开表为核心， 执行数也跟它有关系，所以进度步长由它决定
//            int execCount = tableNames.length;
//            setProgressStepSize(PERCENTAGE / execCount);
//
//            // controller会传要导入哪些表
////            List<MainModalDTO> mainModals = fileListManager.listMainModalByMenuIdByCache(DataConstant.CW_CATEGORY);
//            for (String tableName : tableNames) {
////                Thread.sleep(20000);
//                FileListDTO fileList = fileListManager.getFileListByCache(tableName);
//                List<FileItemDTO> fileItems = fileListManager.listFileItemsByCache(tableName);
//                if (fileItems.size() == 0) {
//                    log.error(tableName + "未配置fileItem_cwgk表头！导入跳过！");
//                } else {
//                    deleteTableData(fileList, new ArrayList<>(ztMap.values()), fromYears1, fromYears2, fromMonths1, fromMonths2, fromDateAllFlag);
//                    insertTableDataByAccess(fromSm, fileList, fileItems, fromDistId, fromYears1, fromYears2, fromMonths1, fromMonths2, fromDateAllFlag, ztMap);
//                    System.out.println(tableName + "完成");
//                }
//                // 设置进度条 完成当前表
//                advanceProgress();
//            }
//            System.out.println("workTable完成");
//
//            // workShenhe 审核全部未审核数据
//            // TODO 这里可能还要生成openReportRecord的数据 也可以当openReportRecord已经有数据 缺再手动生成
//            OpenReportRecordQuery query = new OpenReportRecordQuery();
//            query.setDistNo(toDistId);
//            query.setYwType(PublicConstant.GK_TYPE_CW);
//            query.setYears(Integer.parseInt(fromYears1));
//            query.setMonths(Integer.parseInt(fromMonths1));
//            // 这里设置查询所有未审核的数据 包括待录入status为空的
//            query.setIsAudit(false);
//
//            List<OpenReportRecordDTO> openList = openReportRecordManager.listByCondition(query, PublicConstant.LIST_TYPE_EDIT);
//            for (OpenReportRecordDTO openDTO : openList) {
//                openReportRecordManager.setAuditSuccessAndReadyPublishStatus(openDTO, "AccessImport");
//            }
//            System.out.println("workShenhe完成");
//
//
//            // 提交事务
//            //先进后出提交 否则会出现：Transaction synchronization is not active的错误
//            transactionManagerPrimary.commit(primaryStatus);
//
//            //根据自己的业务情况进行返回
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            // 回滚事务
//            //先进后出提交 否则会出现：Transaction synchronization is not active的错误
//            transactionManagerPrimary.rollback(primaryStatus);
//            throw new RuntimeException(e);
//        }
//    }


//    private void deleteTableData(FileListDTO fileList, List<String> ztIds, String fromYears1, String fromYears2, String fromMonths1, String fromMonths2, boolean isAllDate) {
//        String deleteSQL = "delete from \"" + fileList.getFileName() + "\" where zth in (:ztIds) ";
//        Map<String, Object> params = new HashMap<>();
//        if (!isAllDate) {
//            if (fileList.getPublicType() == PublicType.YEAR) {
//                deleteSQL += " and years>=:fromYears and years<=:toYears";
//                params.put("fromYears", fromYears1);
//                params.put("toYears", fromYears2);
//            } else {
//                deleteSQL += " and (years*100+months)>=:fromYearMonth and (years*100+months)<=:toYearMonth";
//                params.put("fromYearMonth", fromYears1 + fromMonths1);
//                params.put("toYearMonth", fromYears2 + fromMonths2);
//            }
//        }
//
//        params.put("ztIds", ztIds);
//        EntityManagerUtil.update(entityManager, deleteSQL, params);
//    }
//
//    private void insertTableDataByAccess(Statement fromSm, FileListDTO fileList, List<FileItemDTO> fileItems, String fromDistId, String fromYears1,
//                                         String fromYears2, String fromMonths1, String fromMonths2, boolean fromDateAllFlag,
//                                         Map<String, String> ztMap) throws Exception {
//        String tableName = fileList.getFileName();
////        List<FileItemDTO> fileItems = fileListManager.listFileItemsByCache(tableName);
//
//        // 检验是否有months字段
//        List<String> tableColumns = AccessDBUtil.getTableColumns(fromSm, tableName);
//        boolean hasMonths = tableColumns.contains("months") || tableColumns.contains("Months");
//        if (!hasMonths && (fileList.getPublicType() != PublicType.YEAR)) {
//            throw new RuntimeException("查询access子表数据时报错：" + tableName + "不是年表，但没有months列！");
//        }
//
//        // 查询access中的数据 是按照年份和月份区间将所有数据全部查询出来
//        List<String> fields = ListUtil.toSingleList(fileItems, FileItemDTO::getFieldName);
//        String columnSql = StringUtil.join(fields, ", ") + ", years, " + (hasMonths ? "months, " : "") + "zth ";
//        String sql = "select " +
//                columnSql +
//                " from [" +
//                tableName +
//                "] where zth in ( select zth from zt where ztparent like '" +
//                fromDistId + "%')";
//        if (!fromDateAllFlag) {
//            if (fileList.getPublicType() == PublicType.YEAR) {
//                sql += " and years>=" + fromYears1 + " and years<=" + fromYears2;
//            } else {
//                sql += " and (years*100+months)>=" + fromYears1 + fromMonths1 + " and (years*100+months)<=" + fromYears2 + fromMonths2;
//            }
//            sql += " order by " + (StringUtil.isEmpty(fileList.getOrderField()) ? "serial" : fileList.getOrderField());
//        }
//
//        List<List<Object>> accessDataList;
//        try {
//            accessDataList = AccessDBUtil.getList(fromSm, sql);
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//            throw new RuntimeException("查询access数据失败：" + sql + ", " + throwable.getMessage());
//        }
//
//        List<Map<String, Object>> dataList = new ArrayList<>();
//        for (List<Object> accessData : accessDataList) {
//            Map<String, Object> dataMap = new HashMap<>();
//            for (int i = 0; i < fields.size(); i++) {
//                dataMap.put(fields.get(i).toUpperCase(), accessData.get(i));
//            }
//            int count = fields.size();
//            dataMap.put("YEARS", accessData.get(count));
//            count++;
//            if (hasMonths) {
//                dataMap.put("MONTHS", accessData.get(count));
//                count++;
//            }
//            String ztId = ztMap.get((String) accessData.get(count));
//            if (ztId != null) {
//                dataMap.put("ZTID", ztId);
//                dataList.add(dataMap);
//            }
//        }
//
//        baseDataManager.insertTableDataByArray(dataList, fileList, fileItems);
////        Map<String, List<Map<String, Object>>> tableData = new HashMap<>();
////        tableData.put(tableName, dataList);
//
//        // 保存进数据库
////        TableDataDTO subTableDataDTO = new TableDataDTO();
////        subTableDataDTO.setYears(Integer.parseInt(fromYears1));
////        subTableDataDTO.setMonths(Integer.parseInt(fromMonths1));
////        subTableDataDTO.setZtId(toDistNo);
////        subTableDataDTO.setTableName(tableName);
////        subTableDataDTO.setDistNo(toDistNo);
////        subTableDataDTO.setTableData(objectMapper.writeValueAsString(tableData));
////        baseDataManager.saveTableData(subTableDataDTO, fileList, fileItems);
//
//    }


}
